09. Chaining Promises

Chaining Promises Heading

Chaining Promises - Dependent GET and POST Requests

ND#0001 C3 L4 A06 Chaining Promises

Chaining Promises Prep Part III

Notice we have set up a helper function to use fetch to make an async GET request for a route that is made to simulate the Animal Info Web API we are using as an example.

Inside .then() we could call another async function to make a POST request to store this data in our app. Assuming a POST route has been setup on the server side to add data it received to the app endpoint, we could simply call the function we have been using to create POST requests on the client side and pass it the POST route url and the data we want to save to our app. The only tricky part (which can also be fun!), is that we need to use the returned data, and data that we retrieve from a DOM element to create the structure for our POST request.

As a reminder, the postData() function takes a URL, and a data object as parameters. To build the data object using data received from the previous fetch call we can use dot notation. So we could set our first elements like this:

postData('/addAnimal', {animal:data.animal, fact: data.fact} )

But we also want to include the users favorite thing about the animal, which we can add using the variable name which selects the textarea where the users response is. So our final code for creating a POST route to save the data to our app would look like this:

postData('/addAnimal', {animal:data.animal, fact: data.fact, fav:favFact} )

Chaining Promises Heading Example II

Then on the server side to actually add the sent data to our app, we would use this code:

app.post('/addAnimal', addAnimal);

function addAnimal(req,res){

  newEntry = {
    animal: req.body.animal,
    facts: req.body.fact,
    fav: req.body.fav
  }

  animalData.push(newEntry)
  console.log(animalData)
}

ND#0001 C3 L4 A07 Chaining Promises Example

Chaining Promises Quiz

Which of the following is true about working with Promises?

SOLUTION:
  • Chaining Promises with `.then()` allows you to make multiple dependent HTTP requests.

Chaining Promises Summary

Great! Now let’s finally learn how to update the UI of an app with the data gathered from requests and routes.